package handler

import (
	"Gin/api/request"
	"Gin/global/model"
	"Gin/global/pkg"
	context2 "context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"serve/videoSrv"
	"strings"
)

func VideoPush(context *gin.Context) {
	var VideoPushRequest request.VideoPushRequest
	if err := context.ShouldBind(&VideoPushRequest); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	if VideoPushRequest.Title == "" {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "title is null",
		})
		return
	}
	vfile, vm, err := context.Request.FormFile("video")
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	ext := path.Ext(vm.Filename)
	if !strings.Contains(".mp4.avi", ext) {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "not mp4",
		})
		return
	}
	vurl, err := pkg.UploadFile(vfile, vm)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	ifile, im, err := context.Request.FormFile("image")
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	iurl, err := pkg.UploadFile(ifile, im)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	context.Request.ParseForm()
	user_id_jaon := context.Request.Form.Get("UserId")
	var UserId int64
	json.Unmarshal([]byte(user_id_jaon), &UserId)
	_, err = model.VideoClient.VideoPush(context2.Background(), &videoSrv.VideoPushRequest{
		UserId:   UserId,
		ClassId:  VideoPushRequest.ClassId,
		Viper:    VideoPushRequest.Viper,
		Url:      vurl,
		ImageUrl: iurl,
		Title:    VideoPushRequest.Title,
		Len:      VideoPushRequest.Len,
	})
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data":    vurl,
	})
}
